package com.gek.gekapiinterface.controller;

import cn.hutool.core.util.StrUtil;
import com.gek.gekclientsdk.model.User;
import com.gek.gekclientsdk.utils.SignUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/name")
public class NameController {
    @GetMapping("/")
    public String getNameByGet(String name){
        return "your name is "+name;
    }
    @PostMapping("/")
    public String getNameByPost( @RequestParam(value = "name") String name){
        return "your name is "+name;
    }
    @PostMapping("/post")
    public String getNameByPost(@RequestBody User user, HttpServletRequest request) throws Exception {
        String accessKey = request.getHeader("accessKey");
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        String body = request.getHeader("body");
        String sign = request.getHeader("sign");
        //TODO这个实际应该从数据库读取
        String secretKey = "PW14asv2024";
        //TODO 实际应该从数据库查出对应的accessKey
        if (!accessKey.equals("gek")) {
            throw new Exception("accessKey is not correct");
        }
        //TODO 随机数验证,客户端请求过来不存在则存到redis中，给有效期，
        // 如果存在则判断这个key是否在有限期内，如果在则拒绝请求
        // 下面的逻辑实际业务要改
        if(StrUtil.isBlank(nonce)){
            throw new Exception("nonce is not exist");
        }
        //判断时间是否在五分钟内
        if(System.currentTimeMillis() - Long.parseLong(timestamp) > 300000){
            throw new Exception("请求过期");
        }
        String serverSign = SignUtils.genSign(body, secretKey);
        if(!sign.equals(serverSign)){
            throw new Exception("sign is not match");
        }
        return "your name is "+user.getName();
    }
}
